const db = require("../../db/index");
const fs=require('fs')
const path=require("path");
const { v4: uuidv4 } = require('uuid');


// 获取所有消息
exports.getMsgs = (req, res) => {
  const sql = `select * from message`;
  db.query(sql, (err, results) => {
    res.send({
      status: 0,
      message: "获取消息成功",
      data: results,
    });
  });
};

// 添加消息
exports.addMsgs = (req, res) => {
  //将图片文件写进文件夹中
  const str=uuidv4();
  if (req.file) {
    fs.writeFile(path.resolve(__dirname,"../../public/imgs")+"/" +str+"--RAIN--"+ req.file.originalname, req.file.buffer, (err) => {
      if (err) {
        return res.send("图片上传失败");
      }
      req.body.pic = "/imgs/"+str+"--RAIN--"+req.file.originalname;

      const sql = `insert into message set ?`;
      db.query(sql, req.body, (err, results) => {
        if (results.affectedRows !== 1) return res.cc("添加消息失败");
        res.send({
          status: 0,
          message: "添加消息成功",
          data: results,
        });
      });

    });
  }
 
};
